package com.future.cb.web.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogInterceptor implements HandlerInterceptor{
	private static int maxOutputLengthOfParaValue = 512;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			
			log.debug("\n\n\n");
			log.debug("----------Action Report begin------------------------------------------------------");
			// 记录下请求内容
			log.debug("Url        : " + request.getRequestURL().toString());
			log.debug("Method     : " + request.getMethod());
			log.debug("Ip         : " + request.getRemoteAddr());
			log.debug("Controller : " + method.getMethod().getDeclaringClass().getName());
			log.debug("Method     : " + method.getMethod().getName());
			log.debug("Parameters : " + getReqParas(request));
			log.debug("----------Action Report end----------------------------------------------------------");
			log.debug("\n\n\n");
			
		}
		return true;
	}
	/**
	 * 从request中获取parameters展示给日志
	 * @param request
	 * @return
	 */
	private String getReqParas(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		Enumeration<String> e = request.getParameterNames();
		if (e.hasMoreElements()) {
			while (e.hasMoreElements()) {
				String name = e.nextElement();
				String[] values = request.getParameterValues(name);
				if (values.length == 1) {
					sb.append(name).append("=");
					if (values[0] != null && values[0].length() > maxOutputLengthOfParaValue) {
						sb.append(values[0].substring(0, maxOutputLengthOfParaValue)).append("...");
					} else {
						sb.append(values[0]);
					}
				}
				else {
					sb.append(name).append("[]={");
					for (int i=0; i<values.length; i++) {
						if (i > 0)
							sb.append(",");
						sb.append(values[i]);
					}
					sb.append("}");
				}
				sb.append("  ");
			}
			sb.append("\n");
		}
		return sb.toString();
	}
	
}
